package com.example.origin.finance.filter;

import cn.hutool.db.ThreadLocalConnection;
import cn.hutool.extra.servlet.ServletUtil;
import com.example.origin.finance.utils.InheritableThreadLocalUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

@WebFilter(filterName = "WebRequestFilter", urlPatterns = "/*")
public class WebRequestFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = ServletUtil.getHeader(request, "xueqiuCookie", Charset.defaultCharset());
        RequestContextHolder.currentRequestAttributes().setAttribute("xueqiuCookie", header, RequestAttributes.SCOPE_REQUEST);
        InheritableThreadLocalUtil.set(header);
        RequestContextHolder.currentRequestAttributes().registerDestructionCallback("xueqiuCookie", InheritableThreadLocalUtil::remove,RequestAttributes.SCOPE_REQUEST);
        filterChain.doFilter(request, response);
    }
}
